using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Text;
using System.Text.Json;

namespace DocumentCreationSystem.Services;

/// <summary>
/// RWKV模型服务 - 仅支持API调用
/// </summary>
public class RWKVService : IAIService
{
    private readonly ILogger<RWKVService> _logger;
    private readonly HttpClient _httpClient;
    private AIModel? _currentModel;
    private readonly List<AIModel> _availableModels = new();
    private RWKVConfig _config = new();

    public RWKVService(ILogger<RWKVService> logger, HttpClient httpClient)
    {
        _logger = logger;
        _httpClient = httpClient;
        _httpClient.Timeout = TimeSpan.FromSeconds(120); // 120秒，符合API请求最佳实践
    }

    public async Task<List<AIModel>> GetAvailableModelsAsync()
    {
        try
        {
            // 从RWKV API获取模型列表
            await DetectAvailableModelsAsync();

            _logger.LogInformation($"获取到{_availableModels.Count}个RWKV模型");
            return _availableModels.ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取RWKV模型列表失败");
            return new List<AIModel>();
        }
    }

    private async Task DetectAvailableModelsAsync()
    {
        try
        {
            var response = await _httpClient.GetAsync($"{_config.BaseUrl}/v1/models");
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                var modelsResponse = JsonSerializer.Deserialize<ModelsResponse>(content);
                
                _availableModels.Clear();
                if (modelsResponse?.Data != null)
                {
                    foreach (var model in modelsResponse.Data)
                    {
                        _availableModels.Add(new AIModel
                        {
                            Id = model.Id,
                            Name = model.Id,
                            Description = $"RWKV模型 - {model.Id}",
                            Provider = "RWKV"
                        });
                    }
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "从RWKV API检测模型失败");
        }
    }

    public async Task<bool> SetCurrentModelAsync(string modelId)
    {
        var model = _availableModels.FirstOrDefault(m => m.Id == modelId);
        if (model == null)
        {
            _logger.LogWarning($"RWKV模型不存在: {modelId}");
            return false;
        }

        // 检查模型是否可用
        if (!await CheckModelAvailabilityAsync(modelId))
        {
            _logger.LogWarning($"RWKV模型不可用: {modelId}");
            return false;
        }

        _currentModel = model;
        _logger.LogInformation($"切换到RWKV模型: {model.Name}");
        return true;
    }



    private async Task<bool> CheckModelAvailabilityAsync(string modelId)
    {
        try
        {
            var response = await _httpClient.GetAsync($"{_config.BaseUrl}/v1/models");
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                var modelsResponse = JsonSerializer.Deserialize<ModelsResponse>(content);
                return modelsResponse?.Data?.Any(m => m.Id == modelId) == true;
            }
            return false;
        }
        catch
        {
            return false;
        }
    }

    public AIModel? GetCurrentModel()
    {
        return _currentModel;
    }

    public async Task<string> GenerateTextAsync(string prompt, int maxTokens = 2000, float temperature = 0.7f)
    {
        if (_currentModel == null)
        {
            throw new InvalidOperationException("未设置当前RWKV模型");
        }

        try
        {
            var requestBody = new
            {
                model = _currentModel.Id,
                prompt = prompt,
                max_tokens = maxTokens,
                temperature = temperature,
                stream = false
            };

            var json = JsonSerializer.Serialize(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            // 添加API密钥（如果有）
            if (!string.IsNullOrEmpty(_config.ApiKey))
            {
                _httpClient.DefaultRequestHeaders.Authorization = 
                    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _config.ApiKey);
            }

            var response = await _httpClient.PostAsync($"{_config.BaseUrl}/v1/completions", content);
            
            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var completionResponse = JsonSerializer.Deserialize<CompletionResponse>(responseContent);
                
                if (completionResponse?.Choices?.Length > 0)
                {
                    return completionResponse.Choices[0].Text ?? "";
                }
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                _logger.LogError($"RWKV API请求失败: {response.StatusCode}, {errorContent}");
                throw new HttpRequestException($"RWKV API请求失败: {response.StatusCode}");
            }

            return "";
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "RWKV文本生成失败");
            throw;
        }
    }

    public void UpdateConfig(RWKVConfig config)
    {
        _config = config ?? new RWKVConfig();
        _httpClient.BaseAddress = new Uri(_config.BaseUrl);
        _logger.LogInformation($"RWKV配置已更新: {_config.BaseUrl}");
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }

    // 其他IAIService接口方法的简单实现
    public Task<string> PolishTextAsync(string text, string style = "通用") =>
        GenerateTextAsync($"请润色以下文本，风格要求：{style}\n\n原文：\n{text}", 2000, 0.3f);

    public Task<string> ExpandTextAsync(string text, int targetLength, string? context = null) =>
        GenerateTextAsync($"请将以下文本扩写到约{targetLength}字：\n{text}\n\n上下文：{context ?? "无"}", targetLength + 500, 0.7f);

    public Task<string> GenerateChapterAsync(string outline, string? context = null, int targetWordCount = 6500) =>
        GenerateTextAsync($"根据以下大纲创作约{targetWordCount}字的章节：\n{outline}\n\n上下文：{context ?? "无"}", targetWordCount * 2, 0.8f);

    public Task<ConsistencyCheckResult> CheckConsistencyAsync(string currentText, string previousContext) =>
        Task.FromResult(new ConsistencyCheckResult { IsConsistent = true, ConfidenceScore = 0.8f });

    public Task<string> GenerateOutlineAsync(string description, string outlineType) =>
        GenerateTextAsync($"请为以下内容生成{outlineType}大纲：\n{description}", 2000, 0.7f);

    public async Task<List<CharacterInfo>> ExtractCharacterInfoAsync(string text)
    {
        try
        {
            var prompt = $"请从以下文本中提取角色信息，包括姓名、描述、特征等：\n{text}";
            var result = await GenerateTextAsync(prompt, 1000, 0.5f);

            // 简单解析，实际应用中可以使用更复杂的解析逻辑
            var characters = new List<CharacterInfo>();
            var lines = result.Split('\n', StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                if (line.Contains("姓名") || line.Contains("角色"))
                {
                    characters.Add(new CharacterInfo
                    {
                        Name = line.Trim(),
                        Description = "从RWKV模型提取的角色信息"
                    });
                }
            }

            return characters;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "提取角色信息失败");
            return new List<CharacterInfo>();
        }
    }
}

// 辅助类
public class ModelsResponse
{
    public ModelInfo[]? Data { get; set; }
}

public class ModelInfo
{
    public string Id { get; set; } = "";
}

public class CompletionResponse
{
    public Choice[]? Choices { get; set; }
}

public class Choice
{
    public string? Text { get; set; }
}
